import {Injectable, ExecutionContext } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Repository } from "typeorm";
import { TokenEntity } from "../../ShareModule/entities/token.entity";

@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt"){
    constructor(private readonly tokenRepository:Repository<TokenEntity>){
        super();
    }

    canActivate(context:ExecutionContext){
        //add custom authentication
        //通过请求头中携带的参数token来查询数据库。如果token存在，则校验通过，否则校验失败；
        const request = context.switchToHttp().getRequest();
        const token = request.headers.token;

        if(token) {
            const result = async()=>{
                return await this.tokenRepository.findOne({token});
            }
        }

        return super.canActivate(context);
    }

    handleRequest(err,user,info){
        if(err || !user){
            console.log(info)
            throw err;
        }

        return user;
    }

}